from flask import Flask, jsonify
from flask_cors import CORS
from qcloud_cos import CosConfig, CosS3Client
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = Flask(__name__)
CORS(app)  # 允许跨域请求

# COS配置（替换为您的实际信息）
COS_CONFIG = {
    'bucket_name': 'hujiaqi-1358073331',
    'region': 'ap-guangzhou',
    'secret_id': 'AKIDuuiJhsqa9UbUWbklojfYDfvxlNn2A8tQ',
    'secret_key': 'Ogw7BEvSnvpUwHWkrwwnStENI0UnvqY2',
    'detections_folder': 'fire_detections/'  # 检测结果存储目录
}

# 初始化COS客户端
cos_config = CosConfig(
    Region=COS_CONFIG['region'],
    SecretId=COS_CONFIG['secret_id'],
    SecretKey=COS_CONFIG['secret_key']
)
cos_client = CosS3Client(cos_config)

@app.route('/api/detections', methods=['GET'])
def get_detections():
    """获取所有检测结果图片信息"""
    try:
        # 获取COS中的检测结果文件
        response = cos_client.list_objects(
            Bucket=COS_CONFIG['bucket_name'],
            Prefix=COS_CONFIG['detections_folder'],
            MaxKeys=1000
        )

        detections = []
        if 'Contents' in response:
            for item in response['Contents']:
                if not item['Key'].endswith('/'):  # 排除目录本身
                    # 构建图片访问URL
                    image_url = f"https://{COS_CONFIG['bucket_name']}.cos.{COS_CONFIG['region']}.myqcloud.com/{item['Key']}"
                    
                    detections.append({
                        'filename': item['Key'].split('/')[-1],  # 文件名
                        'url': image_url,  # 完整访问URL
                        'size': item['Size'],  # 文件大小(字节)
                        'last_modified': item['LastModified'],  # 最后修改时间
                        'storage_class': item['StorageClass']  # 存储类型
                    })

        return jsonify({
            'count': len(detections),
            'detections': detections
        }), 200

    except Exception as e:
        logger.error(f"获取检测结果失败: {str(e)}")
        return jsonify({
            'error': '获取检测结果失败',
            'message': str(e)
        }), 500

@app.route('/api/health', methods=['GET'])
def health_check():
    """健康检查接口"""
    return jsonify({'status': 'healthy'}), 200

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)